<template>
	<div class="main-container">
		<el-card class="box-card !border-none" shadow="never">

			<div class="flex justify-between items-center">
				<span class="text-page-title">{{ pageName }}</span>
			</div>

			<el-card class="box-card !border-none my-[10px] table-search-wrap" shadow="never">
				<el-form :inline="true" :model="orderTable.searchParam" ref="searchFormRef">
					<el-form-item :label="t('orderRefundNo')" prop="order_refund_no">
						<el-input v-model.trim="orderTable.searchParam.order_refund_no" :placeholder="t('orderRefundNoPlaceholder')" @keyup="filterNumber($event)" maxlength="30" />
					</el-form-item>
					<el-form-item :label="t('createTime')" prop="create_time">
						<el-date-picker v-model="orderTable.searchParam.create_time" type="datetimerange"
							value-format="YYYY-MM-DD HH:mm:ss" :start-placeholder="t('startDate')"
							:end-placeholder="t('endDate')" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="loadOrderList()">{{ t('search') }}</el-button>
						<el-button @click="resetForm(searchFormRef)">{{ t('reset') }}</el-button>
						<el-button type="primary" @click="exportEvent">{{ t('export') }}</el-button>
					</el-form-item>
				</el-form>
			</el-card>
			<el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
				<el-tab-pane :label="t('all')" name=""></el-tab-pane>
				<el-tab-pane :label="t('applyForRefund')" name="1"></el-tab-pane>
				<el-tab-pane :label="t('refundEnd')" name="8"></el-tab-pane>
				<el-tab-pane :label="t('toBeReturned')" name="2"></el-tab-pane>
				<el-tab-pane :label="t('receivedGoods')" name="4"></el-tab-pane>
				<el-tab-pane :label="t('refundRefuse')" name="3"></el-tab-pane>
			</el-tabs>
			<div>
				<el-table :data="orderTable.data" size="large" class="table-top">
					<el-table-column :label="t('goodsInfo')" min-width="240" />
					<el-table-column :label="t('goodsMoney')" min-width="120" />
					<el-table-column :label="t('realityMoney')" min-width="120" />
					<el-table-column :label="t('buyMember')" min-width="120" />
					<el-table-column :label="t('refundMoney')" min-width="120" />
					<el-table-column :label="t('refundType')" min-width="120" />
					<el-table-column :label="t('createTime')" min-width="120" />
					<el-table-column :label="t('refundStatus')" min-width="120" />
					<el-table-column :label="t('operation')" fixed="right" align="right" min-width="120" />
				</el-table>
				<div class="table-body min-h-[150px]" v-loading="orderTable.loading">
					<div v-if="!orderTable.loading">
						<template v-if="orderTable.data.length">
							<div v-for="(item, index) in orderTable.data" :key="index">
								<div class="flex items-center justify-between bg-[#f7f8fa] mt-[10px] border-[#e4e7ed] border-solid border-b-[1px] px-3 h-[35px] text-[12px] text-[#666]">
									<div>
										<span class="ml-5">{{ t('orderRefundNo') }}：{{ (item as any).order_refund_no }}</span>
									</div>
								</div>

								<el-table :data="(item as any).goods" size="large" :span-method="arraySpanMethod" :show-header="false">
									<el-table-column align="left" min-width="240">
										<template #default="{ row }">
											<div class="flex cursor-pointer">
												<div v-if="!['2', '6'].includes(row.alcohol_type)" class="flex items-center min-w-[50px] mr-[10px]">
													<img class="w-[50px] h-[50px]" v-if="row.goods_image_thumb_small" :src="img(row.goods_image_thumb_small)" alt="">
													<img class="w-[50px] h-[50px]" v-else src="" alt="">
												</div>
												<div class="flex  flex-col">
														<el-tooltip class="box-item" effect="light" placement="top">
															<template #content>
																	<div class="max-w-[250px]">{{row.goods_name}}</div>
															</template>
													    <p class="multi-hidden">{{ row.goods_name }}</p>
														</el-tooltip>
													<span class="text-[12px] text-[#999] truncate">{{ row.sku_name }}</span>
												</div>
											</div>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default="{ row }">
											<div class="flex flex-col">
												<span class="text-[14px]">￥{{ row.goods_money }}</span>
											</div>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default="{ row }">
											<div class="flex flex-col">
												<span class="text-[14px]">￥{{ parseFloat(row.goods_money - row.discount_money).toFixed(2) }}</span>
												<div class="text-[14px]" v-if="['5', '6', '7', '8'].includes(item.order?.alcohol_type)">(含包材:￥{{item.order?.bc_money}})</div>
											</div>
										</template>
									</el-table-column>
									<el-table-column min-width="120"  class-name="border-0 border-l-[1px] border-solid border-[var(--el-table-border-color)]">
										<template #default>
											<el-button link type="primary" @click="memberEvent(item.member.member_id)" v-if="item.member">{{ item.member.nickname }}</el-button>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default>
											<span class="text-[14px]" v-if="item.status == 8">￥{{ item.money }}</span>
											<span class="text-[14px]" v-else>￥{{ item.apply_money }}</span>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default>
											<span class="text-[14px]">{{ item.refund_type_name }}</span>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default>
											<span class="text-[14px]">{{ item.create_time }}</span>
										</template>
									</el-table-column>
									<el-table-column min-width="120">
										<template #default>
											<span class="text-[14px]">{{ item.status_name }}</span>
										</template>
									</el-table-column>
									<el-table-column align="right" min-width="120">
										<template #default="{ row }">
											<el-button v-if="['2', '6'].includes(row.alcohol_type)" type="primary" link @click="lookQuestionnaire(row)">{{ t('lookNeedQuestionnaire') }}</el-button>
											<el-button type="primary" link @click="detailEvent(item)">{{ t('info') }}</el-button>
										</template>
									</el-table-column>
								</el-table>
								<div v-if="item.shop_remark" class="text-[14px] h-[30px] leading-[30px] px-3 bg-[#fff0e5] text-[#ff7f5b]">
									<span class="mr-[5px]">{{ t('notes') }}：</span>
									<span>{{ item.shop_remark }}</span>
								</div>
							</div>
						</template>
						<el-empty v-else :image-size="1" :description="t('emptyData')" />
					</div>
				</div>
				<div class="mt-[16px] flex justify-end">
					<el-pagination v-model:current-page="orderTable.page" v-model:page-size="orderTable.limit"
						layout="total, sizes, prev, pager, next, jumper" :total="orderTable.total"
						@size-change="loadOrderList()" @current-change="loadOrderList" />
				</div>
			</div>
		</el-card>
		<order-notes ref="orderNotesDialog" @complete="loadOrderList"></order-notes>
		<export-sure ref="exportSureDialog" :show="flag" type="shop_order_refund" :searchParam="orderTable.searchParam" @close="handleClose" />
		<refund-detail ref="refundDetailDialog" @load="loadOrderList"></refund-detail>
		<need-questionnaire ref="needQuestionnaireDialog" />
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { t } from '@/lang'
import { orderRefund } from '@/addon/shop/api/order'
import { img, filterNumber,setTablePageStorage,getTablePageStorage } from '@/utils/common'
import type { FormInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import refundDetail from '@/addon/shop/views/order/components/refund-detail.vue'
import needQuestionnaire from "@/addon/shop/views/order/components/need-questionnaire.vue"


const route = useRoute()
const router = useRouter()
const pageName = route.meta.title
const activeName = ref('')
const refundDetailDialog: Record<string, any> | null = ref(null)

const customTypes = ref<any>({
    1: '全新定制',
    2: '基于现有酒体优化',
    3: '自行寄样对标调制',
})

interface orderTableType {
	page: number
	limit: number
	total: number
	loading: boolean
	data: any[]
	searchParam: {
		order_refund_no: string
		create_time: string[]
		status: string
	}
}
const orderTable = reactive<orderTableType>({
	page: 1,
	limit: 10,
	total: 0,
	loading: true,
	data: [],
	searchParam: {
		order_refund_no: '',
		create_time: [],
		status: ''
	}
})

const searchFormRef = ref<FormInstance>()

/**
 * 获取订单列表
 */
const loadOrderList = (page: number = 1) => {
	orderTable.loading = true
	orderTable.page = page

	orderRefund({
		page: orderTable.page,
		limit: orderTable.limit,
		...orderTable.searchParam
	}).then(res => {
		let list = <any>res.data.data || [];
		list.forEach((el: any) => {
			let type = el.order?.alcohol_type;
			el.goods = []
			if (['0', '3', '4'].includes(type) || type.length > 1) {
				let plan = el.order_goods?.is_bartender_plan;
				el.goods.push({
					...el.order_goods,
					sku_name: plan == 1 ? '大师基础配方' : plan == 2 ? '标准酒体' : (el.order_goods?.sku_name || '商城订单'),
					rowNum: 1
				});
			} else if (['2', '6'].includes(type)) {
				el.order_alcohol.forEach((item: any) => {
					el.goods.push({
						...item,
						...el.order,
						goods_image_thumb_small: '',
						goods_name: customTypes.value[el.order?.dingzhi_type],
						sku_name: '国匠一杯乐(' + item.order_sku + 'ml)' ,
						goods_money: el.order?.goods_money,
						rowNum: el.order_alcohol.length
					});
				})
			} else if (['7', '8'].includes(type)) {
				el.order_alcohol.forEach((item: any) => {
					el.goods.push({
						...item,
						goods_image_thumb_small: el.goods_sku?.sku_image,
						goods_name: el.goods_sku?.goods?.goods_name,
						sku_name: type == 7 ? '大师基础配方' : '标准酒体',
						goods_money: el.goods_sku?.price,
						rowNum: el.order_alcohol.length
					});
				})
			} else if (['1', '5'].includes(type)) {
				el.order_alcohol.forEach((item: any) => {
					el.goods.push({
						...item,
						goods_image_thumb_small: item.alcohol_body_image,
						goods_name: item.alcohol_body_name,
						sku_name: '勾调一杯乐(' + item.alcohol_sku + 'ml)',
						goods_money: item.alcohol_sku_price,
						rowNum: el.order_alcohol.length
					});
				})
			}
		})
		orderTable.data = list;
		orderTable.total = res.data.total
		setTablePageStorage(orderTable.page, orderTable.limit, orderTable.searchParam);
	}).finally(() => {
		orderTable.loading = false
	})
}
loadOrderList(getTablePageStorage(orderTable.searchParam).page)

// 合并表格行
const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex
}:any) => {
    if (rowIndex === 0) {
        if (columnIndex >= 3) {
            return [row.rowNum, 1]
        } else {
            return [1, 1]
        }
    } else {
        if (columnIndex >= 3) {
            return [0, 0]
        } else {
            return [1, 1]
        }
    }
}

const handleClick = (event: string) => {
	orderTable.searchParam.status = event
	loadOrderList()
}

const needQuestionnaireDialog = ref<any>(null)
// 查看需求问卷
const lookQuestionnaire = (data: any) => {
	
    needQuestionnaireDialog.value.setFormData(data)
}

/**
 * 订单导出
 */
const exportSureDialog = ref(null)
const flag = ref(false)
const handleClose = (val: boolean) => {
	flag.value = val
}
const exportEvent = (data: any) => {
	flag.value = true
}

// 订单详情
const detailEvent = (data: any) => {
    let parameter = {id: data.refund_id};
    refundDetailDialog.value.setFormData(parameter);
    refundDetailDialog.value.showDialog = true;
}

const memberEvent = (id: number) => {
	const routeUrl = router.resolve({
		path: '/member/detail',
		query: { id }
	})
    window.open(routeUrl.href, '_blank')
}

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	loadOrderList()
}
</script>

<style lang="scss" scoped>
.table-top :deep(.el-table__body-wrapper) {
	display: none;
}

:deep(.el-table) {
	--el-table-row-hover-bg-color: var(--el-transfer-border-color);
}

/* 多行超出隐藏 */
.multi-hidden {
	word-break: break-all;
	text-overflow: ellipsis;
	overflow: hidden;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}
</style>
